import {
  getServerSideCategories,
  getServerSideProducts,
} from '@/services/back';
import { Logger, redirectToNoHtml } from '@/utils/back';
import { getCategoryByPaths, parseUrlToFetchParams } from '@/utils/common';
import CategoriesPage from '@/views/Categories';
import { notFound } from 'next/navigation';

export async function generateMetadata({
  params,
}: {
  params: { slug: string[] };
}) {
  const { slug } = params;
  const categoryList = await getServerSideCategories();
  const targetCate = categoryList.find(
    (cate: any) => cate.format_paths === slug.join('/')
  );

  let cateTitle = targetCate?.title || slug[slug.length - 1] || 'my-company';
  if (slug[slug.length - 1].includes('new-arrivals')) {
    cateTitle = 'New Arrivals';
  }
  return {
    title: `${cateTitle} Dropship | Wholesale ${cateTitle} Online`,
    description:
      'aaa',
    keywords: [],
  };
}

const logger = Logger('product-list-page');
export default async function Page(props: any) {
  // console.log('=========== start app/categories/page ===========');
  const categories = await getServerSideCategories();
  const slug = props?.params?.slug;
  // if (!slug) return notFound();
  let paths = slug?.map((p: any) => p.replace(/\.html?$/i, '')) || [];
  const currCategory = getCategoryByPaths(paths, categories);

  const isRedirected = redirectToNoHtml(
    '/categories',
    slug,
    props.searchParams
  );
  if (isRedirected) {
    return;
  }

  // console.log('💡💡:', paths.join('/'), '  categories:', categories?.length);
  // console.log('💡💡:', paths.join('/'));
  let pageTitle = currCategory?.title || 'Products';
  if (paths?.[0] === 'new-arrivals') {
    pageTitle = 'New Arrivals';
    paths = paths.slice(1);
  } else if (paths?.length && !currCategory) {
    logger.warn(
      'current category not found, slug:',
      slug,
      'paths:',
      paths,
      'currCategory:',
      currCategory
    );
    return notFound();
  }
  // const queryParams = parseUrlToFetchParams(
  //   'categories',
  //   paths,
  //   props?.searchParams,
  //   categories
  // );
  // console.log('💡 params >> ', queryParams);
  // const skusInfo = await getServerSideProducts(queryParams);
  // console.log('💡 result skus >>', skusInfo?.result?.length);
  const skusInfo = null;
  return (
    <CategoriesPage
      {...props}
      paths={paths}
      // filters={queryParams}
      pageTitle={pageTitle}
      category={currCategory}
      categories={categories || []}
      products={skusInfo || {}}
    />
  );
}
